/* eslint-disable no-console */

import axios from 'axios'
import cookie from 'vue-cookies'
import { ElMessage } from 'element-plus'
import router from '@/router'

const http = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

// 请求拦截
http.interceptors.request.use(
  config => {
    // 语言类型
    config.headers.locale = cookie.get('bbcLanguage') || 'zh_CN'
    if (config.url == '/p/user/recentBrowse') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    } else {
      config.headers['Content-Type'] = 'application/json; charset=utf-8'
    }
    const token = cookie.get('bbcToken')
    if (token && (config.url.indexOf('/p/') === 0 || config.url == '/user/registerOrBindUser')) {
      config.headers.Authorization = token
    }
    if (config.url == '/p/user/conversations' || config.url == '/p/user/recentBrowse') {
      config.url = import.meta.env.VITE_APP_IM_API + config.url
    } else {
      config.url = import.meta.env.VITE_APP_BASE_API + config.url
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截
http.interceptors.response.use(
  response => {
    const responseData = response.data
    if (responseData.success && responseData.code === '00000') {
      return Promise.resolve(responseData)
    } else if (responseData.code === 'A00002') {
      return Promise.resolve(responseData)
    } else {
      // 未授权
      if (responseData.code === 'A00004') {
        const showLogin = !response.config.dontShowLogin
        cookie.remove('bbcToken')

        // 清除用户信息
        useUserStore().setUser({
          nickName: '',
          userAvatar: ''
        })
        if (location.pathname.indexOf('user') > -1 || location.pathname.indexOf('order') > -1) {
          router.push('/login')
        } else {
          bus.emit('showLogin', showLogin) // 全局事件
        }
      } else if (responseData.code === 'A00001') {
        // 订单接口错误不显示提示
        if (response.config.url.includes('/p/myOrder/orderDetail')) {
          return Promise.reject(response)
        }
        // A00001 用于直接显示提示用户的错误，内容由输入内容决定
        ElMessage({
          message: responseData.msg || 'Error',
          type: 'error',
          duration: 1500
        })
        return Promise.reject(response)
      } else if (responseData.code === 'A00005') {
        // 出小差
        ElMessage({
          message: '服务器出了点小差~',
          type: 'error',
          duration: 1500
        })
        console.error('============== 请求异常 ==============')
        console.log('接口地址: ', response.config.url.replace(import.meta.env.VITE_APP_BASE_APIpath, ''))
        console.log('异常信息: ', responseData)
        console.error('============== 请求异常 end ==========')
      }
      return Promise.reject(response)
    }
  },
  error => {
    console.log('error', error)
  }
)
const uploadFile = function (url, file) {
  return axios.put(url, file)
}
export default http
export { uploadFile }
